<!--
main.vue 交易查询
-->
<template>
  <div class="app-container  flex-cloumn" >
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :rules="rules"
             label-width="68px">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="合约编号">
            <el-input
                clearable
                size="small"
                :style="{width: '100%'}"
                @bulr="handleQuery"
                placeholder="合约编号"
                v-model="queryParams.iCodeCond"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="挂钩标的" prop="instrument">
            <baseCombox url="/marketdata/instrument/getInstruments.action" clearable
                        size="small"
                        multiple collapse-tags collapse-tags-tooltip
                        valueField="code"
                        labelField="productName" placeholder="挂钩标的"
                        v-model="instruments"></baseCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="起始日">
            <el-date-picker
                v-model="queryParams.begDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.begDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="本方账户" prop="accId">
            <baseCombox url="/trade/account/querySelfAccountCombox.action" clearable
                        size="small" multiple collapse-tags collapse-tags-tooltip
                        valueField="accId"
                        labelField="accName"  placeholder="本方账户"
                        v-model="accId"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="期权类型">
            <dictCombox v-model="productType" multiple collapse-tags collapse-tags-tooltip dictType="optionType" size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="到期日">
            <el-date-picker
                v-model="queryParams.endDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.endDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="行权方式" prop="exerciseType">
            <dictCombox v-model="queryParams.exerciseType" :style="{width: '100%'}" dictType="exerciseType"
                        size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="期权状态" prop="duEventStatus">
            <dictCombox v-model="duEventStatus" multiple collapse-tags collapse-tags-tooltip dictType="durationStatus" size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交易日期">
            <el-date-picker
                v-model="queryParams.tradeDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.tradeDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row  :gutter="12">
        <el-col :span="6">
          <el-form-item label="交易对手" prop="partyId">
            <baseCombox url="/trade/counterparty/queryCounterparty4Combox.action" clearable
                        :style="{width: '100%'}"
                        size="small" multiple collapse-tags collapse-tags-tooltip
                        valueField="partyId" labelField="partyName" placeholder="交易对手"
                        v-model="partyId"></baseCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="交易类型">
            <dictCombox v-model="queryParams.tradeTypes"
                        filterKey="OtcOptionSell,OtcOptionBuy"
                        dictType="tradeType" size="small"></dictCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="支付日期">
            <el-date-picker
                v-model="queryParams.paymentDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.paymentDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>


      </el-row>

      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="计算日期" prop="calcDate">
            <el-date-picker
                v-model="queryParams.calcDate"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="买卖方向" prop="payDirection">
            <dictCombox v-model="queryParams.payDirection" dictType="payDirection" size="small"></dictCombox>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-button icon="Search" size="small" style="margin: 3px 3px" type="primary"
                     v-hasPermi="['trade:tradebalance:list']"
                     @click="handleQuery">搜索
          </el-button>
          <el-button icon="ArrowRight" size="small" style="margin: 3px 3px" type="primary" :disabled="single"
                     v-hasPermi="['trade:tradebalance:pric']"
                     @click="handlePricing">定价
          </el-button>
          <el-button
              type="warning"
              style="margin: 3px 3px"
              icon="Download"
              size="small"
              @click="handleExportAll"
              v-hasPermi="['pricing:otctrade:exportAll']"
          >导出
          </el-button>
          <el-button :disabled="isCalc" icon="Plus" size="small" style="margin: 3px 3px" type="primary"
                     v-hasPermi="['trade:tradebalance:calc']"
                     @click="handleCalc">计算
          </el-button>
          <el-button v-if="calTime!=null"
                     type="success"
                     style="margin: 3px 5px"
                     plain disabled="true"
                     size="small"
          >{{ calTime +' '+ calcTimes }}
          </el-button>
          <div v-show="isCalc">
            <el-progress
                :percentage="100"
                status="success"
                :indeterminate="true"
                :duration="5"
            />
          </div>
        </el-col>
      </el-row>
    </el-form>

    <xTable ref="refTradeBalanceTable" v-loading="loading" :data="tradeList" @row-dblclick="handleDbclick"
            class="tableDragger_form"
            border
            multiple="true"
            @selection-change="TradeBalanceTableSelect"
            refId="refTradeBalanceTable">

      <template #columList>
        <el-table-column label="序号" type="index" width="60">
        </el-table-column>
        <el-table-column align="center" label="产品编号" prop="extTradeId" width="200" />
        <el-table-column align="center" label="合约编号" prop="iCode" width="200" />
        <el-table-column align="center" label="期权类型" prop="productType" width="auto"><template #default="scope"> <dict-tag spVal="*" :options="optionType" :value="scope.row.productType"/></template></el-table-column>
        <el-table-column align="center" label="交易日期" prop="tradeDate" width="auto"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="标的代码" prop="uICode" width="auto"/>
        <el-table-column align="center" label="标的名称" prop="uIName" width="100px"/>
        <el-table-column v-if="false" align="center" label="资产类型" prop="uAType" width="auto"/>
        <el-table-column v-if="false" align="center" label="市场类型" prop="uMType" width="auto"/>
        <el-table-column align="center" label="买卖方向" prop="payDirection" width="auto"> <template #default="scope"> <dict-tag :options="payDirection" :value="scope.row.payDirection"/> </template> </el-table-column>
        <el-table-column align="center" label="涨跌类型" prop="optionType" width="auto"> <template #default="scope"> <dict-tag :options="callPut" :value="scope.row.optionType"/>  </template></el-table-column>
        <el-table-column align="center" label="行权方式" prop="exerciseType" width="auto"><template #default="scope"><dict-tag :options="exerciseType" :value="scope.row.exerciseType"/></template></el-table-column>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="高行权价(元)" prop="strikePrice" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="低行权价(元)" prop="lowStrikePrice" width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="收益率1(%)" prop="yield1" width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="收益率2(%)" prop="yield2" width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="收益率3(%)" prop="yield3" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="障碍价1(元)" prop="triggerPrice1" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="障碍价2(元)" prop="triggerPrice2" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="期权费率(%)" prop="frontOptionFeeRate" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="期权费(元)" prop="frontOptionFee" width="100px"/>

        <el-table-column :formatter="(row, column, cellValue)=>{return Boolean(cellValue=='1')?'是':'否'}" align="right" label="期权费年化" prop="frontOptionFeeYear" width="120px"/>
        <el-table-column align="center" label="期权费支付日" prop="frontOptionFeePaydate" width="120px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="前端费率(%)" prop="frontFeeRate" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="前端费(元)" prop="frontFee" width="100px"/>

        <el-table-column :formatter="(row, column, cellValue)=>{return Boolean(cellValue=='1')?'是':'否'}" align="right" label="前端费年化" prop="frontFeeYear" width="120px"/>

        <el-table-column align="center" label="前端费支付日" prop="frontFeePaydate" width="100px"/>
        <el-table-column align="center" label="起始日" prop="issueDate" width="100px"/>
        <el-table-column align="center" label="到期日" prop="maturityDate" width="100px"/>
        <el-table-column align="center" label="到期支付日" prop="paymentDate" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="提前终止费用(元)" prop="terminateFee" width="120px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="期初价格" prop="price" width="100px"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="名义本金(元)" prop="volume" width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="参与率1(%)" prop="participationRate1" width="100px"/>
        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="参与率2(%)" prop="participationRate2" width="100px"/>
<!--        <el-table-column :formatter="formartEmptyTablePercentP2" align="right" label="固定利率(%)" prop="fixedRate" width="100px"/>-->
        <el-table-column align="center" label="期权状态" prop="duEventStatus" width="auto">
          <template #default="scope">
            <!-- <dict-tag :options="durationStatus" :value="moment(scope.row.maturityDate).isBefore(queryParams.calcDate) ? scope.row.eventStatus : scope.row.duEventStatus"/> -->
            <dict-tag :options="durationStatus" :value="scope.row.duEventStatus"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="交易对手" prop="partyName" width="100px"/>
        <el-table-column align="center" label="本方账户" prop="accName" width="100px"/>
        <el-table-column align="center" label="计算日期" prop="calcDate" width="100">
          <template #default="scope">
            {{ scope.row.calcDate == null ? '未估值' : scope.row.calcDate }}
          </template>
        </el-table-column>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="标的行情" prop="calcPrice" width="100">
        </el-table-column>
<!--        <el-table-column :formatter="formartTablePercentP2" align="right" label="收益率(%)" prop="yield" width="130"/>-->
        <el-table-column :formatter="formartTablePercentP2" align="right" label="已实现收益率(%)" prop="realizedYield"
                         width="130"/>
<!--        <el-table-column :formatter="formartTablePercentP2" align="right" label="历史盈亏率(%)" prop="hisYield"
                         width="130"/>-->
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="浮动盈亏(元)" prop="plFloat" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="npv" prop="npv" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="delta" prop="delta" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="deltacash" prop="cashDelta" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="gamma" prop="gamma" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="gammacash" prop="cashGamma" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="theta" prop="theta" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="vega" prop="vega" width="130"/>
        <el-table-column :formatter="formartEmptyTableP2" align="right" label="rho" prop="rho" width="130"/>
        <el-table-column align="center">
          <template #default="scope">
            <el-button size="small" @click="openDetail(scope.$index, scope.row)"
            >详情
            </el-button>
          </template>
        </el-table-column>
      </template>

    </xTable>
    <pagination
        style="margin:20px 0 20px 0"
        v-show="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getTradeList"
    />
    <el-dialog v-model="InstrumentDialogVisible" title="交易详情" width="720px" destroy-on-close="true"
               :close-on-click-modal="false">
      <el-row>
        <el-col span="8">
          <el-card shadow="hover" style="width: 350px;height:100%;margin:3px 0 3px 0;">
            <template #header>
              <div class="option-header">
                <div class="option-header-content"><span>交易要素</span></div>
                <div>

                </div>
              </div>
            </template>
            <div class="optionst01" style="height:100%;">
              <el-form ref="dialog2DocumentForm" :model="InstrumentDialogInstrument.data" disabled>
                <!--          <el-form-item label="组合"  label-width="120px">
                            <baseCombox  url="/pricing/group/queryVGroupCombox.action"
                                         clearable
                                         multiple="true"
                                         valueField="dict_val"
                                         labelField="dict_disp"
                                         size="small"
                                         placeholder="组合"    ></baseCombox>

                          </el-form-item>-->
                <el-form-item label="本方账户" prop="accId" label-width="120px">
                  <baseCombox url="/trade/account/querySelfAccountCombox.action"
                              clearable
                              valueField="accId"
                              labelField="accName"
                              size="small"
                              v-model="InstrumentDialogInstrument.data.accId"
                              :style="{width: '100%'}" placeholder=""></baseCombox>
                </el-form-item>
                <el-form-item label="交易对手" label-width="120px" prop="partyId">
                  <baseCombox v-model="InstrumentDialogInstrument.data.partyId"
                              clearable
                              labelField="partyName"
                              url="/trade/counterparty/queryCounterparty4Combox.action"
                              size="small"
                              valueField="partyId"
                              :style="{width: '100%'}" placeholder=" "></baseCombox>
                </el-form-item>
                <el-form-item label="产品编号" label-width="120px" prop="extTradeId">
                  <el-input v-model="InstrumentDialogInstrument.data.extTradeId" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="合约编号" label-width="120px" prop="iCode">
                  <el-input v-model="InstrumentDialogInstrument.data.iCode" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="交易日期" label-width="120px" prop="tradeDate">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.tradeDate" placeholder="选择日期" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="期初保证金" label-width="120px" prop="margin" v-show="false">
                  <el-row style="width: 100%;">
                    <el-col :span="6">
                      <el-select v-model="InstrumentDialogInstrument.data.amountDirection" placeholder="请选择">
                        <el-option label="支付" value="-1"/>
                        <el-option label="收取" value="1"/>
                      </el-select>
                    </el-col>
                    <el-col :span="18">
                      <InputAmount v-model:value="InstrumentDialogInstrument.data.amount" append="元" autocomplete="off"
                                   placeholder=" "
                                   precision="2"/>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="前端费支付方向" label-width="120px" prop="frontFee">
                  <el-select v-model="InstrumentDialogInstrument.data.frontFeeDirection" placeholder="请选择">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="前端费" label-width="120px" prop="frontFee">
                  <el-row  style="width: 100%;" >
                    <el-col :span="10"><el-checkbox v-model="InstrumentDialogInstrument.data.frontFeeYear" @change="onfrontFeeRateChange()"  name="status" false-label="0" true-label="1">年化
                    </el-checkbox></el-col>

                    <el-col :span="14"> <Numberinput v-model="InstrumentDialogInstrument.data.frontFeeRate" :max="1000000000" :min="0" append="%" width="100%"
                                                     precision="2" @blur="onfrontFeeRateChange()"/></el-col>
                  </el-row>
                  <el-row style="width: 100%;" >
                    <InputAmount v-model:value="InstrumentDialogInstrument.data.frontFee" maxlength="20" append="元" width="100%"
                                 autocomplete="off" @blur="onfrontFeeChange()"
                                 precision="2"/>
                  </el-row>
                </el-form-item>
                <el-form-item label="前端费支付日" label-width="120px" prop="frontFeePaydate">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.frontFeePaydate" placeholder="选择日期" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="期权费支付方向" label-width="120px" prop="fee">
                  <el-select v-model="InstrumentDialogInstrument.data.feeDirection" placeholder="请选择">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="期权费" label-width="120px" prop="fee">
                  <el-row  style="width: 100%;">
                    <el-col :span="10"><el-checkbox v-model= "InstrumentDialogInstrument.data.feeYear" @change="onFeeRateChange()" name="status" false-label="0" true-label="1">年化
                    </el-checkbox></el-col>
                    <el-col :span="14"> <Numberinput v-model="InstrumentDialogInstrument.data.feeRate" :max="1000000000" :min="0" append="%" width="100%"
                                                     precision="2" @blur="onFeeRateChange()"/></el-col>
                  </el-row>
                  <el-row style="width: 100%;" >
                    <InputAmount v-model:value="InstrumentDialogInstrument.data.fee" maxlength="20" append="元" width="100%"
                                 autocomplete="off" @blur="onFeeChange()"
                                 precision="2"/>
                  </el-row>
                </el-form-item>
                <el-form-item label="期权费支付日" label-width="120px" prop="setDate">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.setDate" placeholder="选择日期" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="提前终止日期" label-width="120px" prop="terminateDate" v-show="false">
                  <el-date-picker v-model="InstrumentDialogInstrument.data.terminateDate" placeholder="选择日期" type="date"
                                  value-format="YYYY-MM-DD">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="提前终止费用" label-width="120px" prop="terminateFee" v-show="false">
                  <InputAmount v-model:value="InstrumentDialogInstrument.data.terminateFee" append="元"
                               autocomplete="off"
                               precision="2"/>
                </el-form-item>
                <el-form-item label="备注" label-width="120px" prop="remark">
                  <el-input v-model="InstrumentDialogInstrument.data.remark" autocomplete="off"
                            type="textarea"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
        <el-col span="16">
          <detail :close="closeInstrumentDialog" :instrument="InstrumentDialogInstrument.data"/>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog :close-on-click-modal="false"
               draggable="true"
               :title="tradeTitle"
               v-model="simpleOpen"
               destroy-on-close="true"
               width="630px"
               append-to-body>
      <el-form ref="tradeFromRef">
        <el-form-item label="交易类型">
          <DictCombox v-model="tradeFrom.tradeType" dictType="simpleTradeType" clearable :disabled="disableFlag"
                      style="width:225px"
                      size="small">
          </DictCombox>
          <el-form-item label="本方账户" label-width="120px">
            <baseCombox v-model="tradeFrom.accId"
                        :disabled="disableFlag"
                        :style="{width: '100%'}"
                        clearable
                        labelField="accName"
                        placeholder="本方账户"
                        size="small"
                        style="width:225px"
                        url="/trade/account/querySelfAccountCombox.action" valueField="accId"></baseCombox>
          </el-form-item>
        </el-form-item>
        <el-form-item label="交易日期">
          <el-date-picker
              v-model="tradeFrom.tradeDate"
              :disabled="disableFlag"
              placeholder="选择交易日期"
              size="small"
              style="width:225px"
              type="date"
              value-format="YYYY-MM-DD">
          </el-date-picker>
          <el-form-item label="标的" label-width="120px" prop="instrumenId">
            <Underlyer ref="underlyerIdRef" v-model="tradeFrom.instrumenId" :disabled="disableFlag"
                       :underlyerId="tradeFrom.instrumenId" style="width:225px"/>
          </el-form-item>
        </el-form-item>
        <el-form-item label="数量" label-width="60px">
          <InputAmount v-model:value="tradeFrom.volume" style="width:225px" :disabled="disableFlag"
                       precision="2"></InputAmount>
          <el-form-item label="价格" label-width="120px">
            <InputAmount v-model:value="tradeFrom.price" :disabled="disableFlag" style="width:225px" append="元"
                         precision="2"
            ></InputAmount>
          </el-form-item>
        </el-form-item>
        <el-form-item label="金额" label-width="60px">
          <el-select v-model="tradeFrom.amountDirection" :disabled="disableFlag" placeholder="请选择" style="width:60px">
            <el-option label="支付" value="-1"/>
            <el-option label="收取" value="1"/>
          </el-select>
          <el-form-item>
            <InputAmount :disabled="disableFlag" v-model="tradeFrom.amount" style="width:165px" append="元"
                         precision="2"
            ></InputAmount>
          </el-form-item>
          <el-form-item label="费用" label-width="120px">
            <el-select :disabled="disableFlag" v-model="tradeFrom.feeDirection" placeholder="请选择" style="width:60px">
              <el-option label="支付" value='-1'/>
              <el-option label="收取" value='1'/>
            </el-select>
            <el-form-item>
              <InputAmount :disabled="disableFlag" v-model="tradeFrom.fee" style="width:165px" precision="2"
                           append="元"></InputAmount>
            </el-form-item>
          </el-form-item>
        </el-form-item>
        <el-form-item label="备注" label-width="60px">
          <el-input :disabled="disableFlag" v-model="tradeFrom.remark" :autosize="{ minRows: 4, maxRows: 100 }"
                    style="width:550px"
                    type="textarea"/>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="TradeBalance">
import {calcTrade4OtcOptionByPage, getTrade4OtcOptionByPage, deleteTrade} from '@/api/trade/tradebalance'
import {onActivated} from '@vue/runtime-core'
import Numberinput from '@/xquant/base/number'
import detail from '@/views/calc/otcOtion/pricingdraft/detail.vue'
import Underlyer from '@/xquant/base/underlyer'
import xTable from '@/xquant/base/xTable'
import DictCombox from '@/xquant/base/dictCombox'
import InputAmount from '@/xquant/base/InputAmount'
import {computed, reactive, watch} from 'vue'
import {formartFormP2} from "@/utils/numberUtil";
import {isVoid, isNotVoid, isEqualNum} from '@/utils/util'
import {calcAnnualizedByTerminationPaymentDate} from '@/utils/util'
import moment from 'moment'

const {proxy} = getCurrentInstance()
const store = useStore();
const {
  callPut,
  M_TYPE,
  A_TYPE,
  CURRENCY,
  optionType,
  priceType,
  exerciseType,
  tradeType,
  optionTypePp,
  optionStatus,
  durationStatus,
  payDirection,
  simpleTradeType,
} = proxy.useDict('callPut','M_TYPE', 'A_TYPE', 'CURRENCY', 'optionType', 'optionTypePp', 'priceType', 'exerciseType', 'tradeType', 'optionStatus', 'payDirection', 'durationStatus', 'simpleTradeType')
const tradeList = ref([])
const open = ref(false)
const disableFlag = ref(true)
const simpleOpen = ref(false)
const simpleType = ['LongOpen', 'LongClose', 'ShortClose', 'ShortOpen']
const tradeTitle = '场内交易'
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const selectRows = reactive({
  data: []
})
//索引
const indexs = ref([])
//数据
const rows = ref([])
const instruments = ref([])
const accId = ref([])
const partyId = ref([])
const duEventStatus = ref([])
const single = ref(true)
const single2 = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const screenHeight = ref(document.documentElement.clientHeight - 300 + 'px')
const calTime = ref(null)
const isCalc = ref(false)
const calcTimes = ref('')
const router = useRouter()
const InstrumentDialogVisible = ref(false)
const InstrumentDialogInstrument = reactive({})
const productType = ref([])
const data = reactive({
  tradeFrom: {
    amountDirection: '1',
    feeDirection: '1'
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    iCodeCond: undefined,
    iCodes: undefined,
    tradeIds: undefined,
    optionType: undefined,
    instrument: undefined,
    instruments: undefined,
    tradeDate1: undefined,
    tradeDate2: undefined,
    calcDate: proxy.getSysDate(),
    partyIds: undefined,
    accIds: undefined,
    priceType: 'DP_CLOSE',
    begDate1: undefined,
    begDate2: undefined,
    endDate1: undefined,
    endDate2: undefined,
    productTypes: undefined,
    duEventStatus: undefined,
    payDirection: '',
    exerciseType: '',
    paymentDate1:undefined,
    paymentDate2:undefined
  }
})

const {queryParams, tradeFrom} = toRefs(data)
const rules = reactive({
  calcDate: [{required: true, message: '请选择', trigger: 'change'}],
})
watch(() => queryParams.value.begDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.begDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.begDate2)
    if (a > b) {
      queryParams.value.begDate2 = newVal
    }
  }
})
watch(() => queryParams.value.begDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.begDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.begDate1)
    if (a > b) {
      queryParams.value.begDate1 = newVal
    }
  }
})
watch(() => queryParams.value.endDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.endDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.endDate2)
    if (a > b) {
      queryParams.value.endDate2 = newVal
    }
  }
})
watch(() => queryParams.value.endDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.endDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.endDate1)
    if (a > b) {
      queryParams.value.endDate1 = newVal
    }
  }
})
watch(() => queryParams.value.tradeDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.tradeDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.tradeDate2)
    if (a > b) {
      queryParams.value.tradeDate2 = newVal
    }
  }
})
watch(() => queryParams.value.tradeDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.tradeDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.tradeDate1)
    if (a > b) {
      queryParams.value.tradeDate1 = newVal
    }
  }
})


watch(() => queryParams.value.paymentDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.paymentDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.paymentDate2)
    if (a > b) {
      queryParams.value.paymentDate2 = newVal
    }
  }
})
watch(() => queryParams.value.paymentDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.paymentDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.paymentDate1)
    if (a > b) {
      queryParams.value.paymentDate1 = newVal
    }
  }
})


/** 查询列表 */
function getTradeList() {
  rows.value = []
  loading.value = true
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    queryParams.value.instrument = router.currentRoute.value.query.instrument
    queryParams.value.iCodes = router.currentRoute.value.query.iCodes
    if (proxy.isNotVoid(router.currentRoute.value.query.opexDate)) {
      queryParams.value.calcDate = router.currentRoute.value.query.opexDate
    }
  }
  

  let params = proxy.lsh.cloneDeep(queryParams.value)
  if (queryParams.value.tradeIds != null && queryParams.value.tradeIds != '' && queryParams.value.tradeIds != undefined) {
    params.iCodeCond = null
    params.instruments = null
    params.begDate1 = null
    params.begDate2 = null
    params.accIds = null
    params.productType = null
    params.endDate1 = null
    params.endDate2 = null
    params.exerciseType = null
    params.duEventStatus = null
    params.tradeDate1 = null
    params.tradeDate2 = null
    params.partyIds = null
    params.tradeType = null
    params.paymentDate1 = null
    params.paymentDate2 = null
  } else {
    params.accIds = accId.value.join(',')
    params.instruments = instruments.value.join('|')
    params.productTypes = JSON.stringify(productType.value)
    params.partyIds = partyId.value.join(',')
    params.duEventStatus = JSON.stringify(duEventStatus.value)
  }
  // params.tradeTypes=proxy.lsh.join(params.tradeTypes,',');
  getTrade4OtcOptionByPage(params).then(response => {
    tradeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

onActivated(() => {
  //解决跳转页面不刷新
  getTradeList()
})


/** 搜索按钮操作 */
function handleQuery() {
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) {
      proxy.$modal.msgWarning('请选择计算日期')
    }
    queryParams.value.pageNum = 1
    if (proxy.isNotVoid(router.currentRoute.value.query)) {
      router.currentRoute.value.query = null
      queryParams.value.instrument = null
      queryParams.value.iCodes = null
    }
    queryParams.value.tradeIds = null
    getTradeList()
  })
}

// 删除交易
function handleDelete() {
  proxy.$modal
      .confirm('是否确认删除合约编号为 "' + rows.value[0].iCode + '"的数据项？')
      .then(function () {
        return deleteTrade(rows.value[0])
      })
      .then(() => {
        getTradeList()
        proxy.$modal.msgSuccess('删除成功')
      })
}

/** 计算 */
function handleCalc() {

  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) {
      proxy.$modal.msgWarning('请选择计算日期')
    }
    let params = proxy.lsh.cloneDeep(queryParams.value)
    queryParams.value.tradeIds = null
    var tradeIdsArry = []
    if (rows.value.length > 0) {
      rows.value.forEach(element => {
        tradeIdsArry.push(element.tradeId)
      })
      params.tradeIds = JSON.stringify(tradeIdsArry);
      queryParams.value.tradeIds = JSON.stringify(tradeIdsArry)
    } else {
      params.pageNum = 1
      params.accIds = accId.value.join(',')
      params.instruments = instruments.value.join('|')
      params.productTypes = JSON.stringify(productType.value)
      params.partyIds = partyId.value.join(',')
      params.duEventStatus = JSON.stringify(duEventStatus.value)
    }

    isCalc.value = true
    let startTime = new Date()
    calTime.value = '开始计算: ' + proxy.getCurrTime('YYYY-mm-dd HH:MM:SS', startTime)
    calcTimes.value =  ' 计算时长：'
    const interval = setInterval(()=>{
      let tmp = proxy.$moment.duration(new Date() - startTime)
      calcTimes.value =  ' 计算时长：'+ tmp.minutes()+'分'+tmp.seconds()+'秒'
    })

    calcTrade4OtcOptionByPage(params).then(response => {
      getTradeList()
      isCalc.value = false
      let endTime = new Date()
      clearInterval(interval);
      calTime.value = '刷新时间: ' + proxy.getCurrTime('YYYY-mm-dd HH:MM:SS', endTime)
    })
  })
}

/** 跳转定价页面 */
function handlePricing() {

  if (rows.value.length > 0) {
    let {pForm, pFormPricing, pFormInstrument, tradeId, iCode, productType, pFormResult} = rows.value[0]
      store.commit("RM_Map", '交易重放'+tradeId)
    router.push({
      path: '/calc/OtcOptionRef/index/' + tradeId,
      // name: 'CALC',
      query:
          {
            "dataId": '交易重放'+tradeId,
            'pForm': pForm,
            'pFormInstrument': pFormInstrument,
            'pFormPricing': pFormPricing,
            'productType': productType,
            'pFormResult': pFormResult,
            title: '交易重放' + iCode,
            showTitleDetail: '交易重放' + tradeId
          },
    })
  }
}

function TradeBalanceTableSelect(selection) {
  if (selection.length == 0) {
    indexs.value = []
  } else {
    indexs.value = selection.map(item => item.index)
    rows.value = selection.map(item => item)
  }
  single.value = selection.length != 1
  single2.value = !selection.length
  multiple.value = !selection.length
  if (selection.length == 1) {
    return
  }
  if (selection.length != 1) {

  }

}

function formartTradeType(row, column, cellValue) {
  let fmtValue = '*'
  proxy.lsh.map(tradeType.value, function (o) {
    if (o.value == cellValue) {
      fmtValue = o.label
    }
  })
  return fmtValue
}

/** 导出按钮操作 */
function handleExport() {
  let params = proxy.lsh.cloneDeep(queryParams.value)
  var tradeIdsArry = []
  if (rows.value.length > 0) {
    rows.value.forEach(element => {
      tradeIdsArry.push(element.tradeId)
    })
    params.tradeIds = JSON.stringify(tradeIdsArry);
  } else {
    params.accIds = accId.value.join(',')
    params.instruments = instruments.value.join('|')
    params.productTypes = JSON.stringify(productType.value)
    params.partyIds = partyId.value.join(',')
    params.duEventStatus = JSON.stringify(duEventStatus.value)
  }
  proxy.download('/pricing/trade/exportTradeBanlance.action', {
    ...params
  }, `场外持仓${proxy.getCurrTime('YYYYmmddHHMMSS', new Date())}.xlsx`)
}

/** 导出按钮操作 */
function handleExportAll() {
  let params = proxy.lsh.cloneDeep(queryParams.value)
  var tradeIdsArry = []
  if (rows.value.length > 0) {
    rows.value.forEach(element => {
      tradeIdsArry.push(element.tradeId)
    })
    params.tradeIds = JSON.stringify(tradeIdsArry);
  } else {
    params.pageNum = 1
    params.accIds = accId.value.join(',')
    params.instruments = instruments.value.join('|')
    params.productTypes = JSON.stringify(productType.value)
    params.partyIds = partyId.value.join(',')
    params.duEventStatus = JSON.stringify(duEventStatus.value)
  }
  proxy.download('/pricing/trade/exportTradeBanlance.action', Object.assign({
    ...params
  }, {pageSize: ''}), `场外持仓${proxy.getCurrTime('YYYYmmddHHMMSS', new Date())}.xlsx`)
}

function handleDbclick(row, column, event) {
  if (simpleType.includes(row.tradeType)) {
    tradeFrom.value = row
    tradeFrom.value.instrumenId = row.uICode + ',' + row.aType + ',' + row.mType
    simpleOpen.value = true
    if (tradeFrom.value.amount < 0) {
      tradeFrom.value.amountDirection = '-1'
      tradeFrom.value.amount = Math.abs(tradeFrom.value.amount)
    } else {
      tradeFrom.value.amountDirection = '1'
    }
    if (tradeFrom.value.fee < 0) {
      tradeFrom.value.feeDirection = '-1'
      tradeFrom.value.fee = Math.abs(tradeFrom.value.fee)
    } else {
      tradeFrom.value.feeDirection = '1'
    }
    if (tradeFrom.value.frontFee < 0) {
      tradeFrom.value.frontFeeDirection = '-1'
      tradeFrom.value.frontFee = Math.abs(tradeFrom.value.frontFee)
    } else {
      tradeFrom.value.frontFeeDirection = '1'
    }

  } else {
    let {
      pForm,
      pFormPricing,
      pFormInstrument,
      draftName,
      optionType,
      partyId,
      id,
      pFormResult,
      productType,
      remark,
      setDate,
      margin,
      fee,
      amount,
      tradeDate,
      tradeId,
      accId,
      iCode,
      extTradeId,
      frontFee,
      frontFeeYear,
      frontFeeRate,
      frontOptionFeeYear,
      frontOptionFeeRate,
      frontOptionFee,
      frontFeePaydate,
      terminateDate,
      terminateFee
    } = row
    pFormResult = proxy.lsh.assign(pFormResult,{
      npv: row.npv,
      delta: row.delta,
      deltacash: row.cashDelta,
      gamma: row.gamma,
      gammacash: row.cashGamma,
      theta: row.theta,
      vega: row.vega,
      rho: row.rho,
      npvPercentage: formartFormP2(100 * (Number(row.npv) / Number(row.volume))),
      spotPrice: row.calcPrice,
    })
    let amountDirection = margin < 0 ? '-1' : '1'
    let feeDirection = fee < 0 ? '-1' : '1'
    let frontFeeDirection = frontFee < 0 ? '-1' : '1'

    InstrumentDialogInstrument.data = {
      pForm,
      pFormPricing,
      pFormInstrument,
      draftName,
      optionType,
      setDate,
      id,
      iCode,
      pFormResult,
      remark,
      fee: Math.abs(fee),
      feeYear:frontOptionFeeYear,
      amount: Math.abs(margin),
      frontFeeYear,
      frontFeeRate,
      feeRate: frontOptionFeeRate,
      tradeDate,
      tradeId,
      accId,
      partyId, amountDirection, feeDirection,
      extTradeId,
      frontFeeDirection,
      frontFee:Math.abs(frontFee),
      frontFeePaydate,
      terminateDate,
      terminateFee
    }
    InstrumentDialogInstrument.data.optionType = productType
    InstrumentDialogInstrument.data.fee = Math.abs(frontOptionFee)
    InstrumentDialogInstrument.data.feeRate = frontOptionFeeRate
    InstrumentDialogInstrument.data.feeYear = frontOptionFeeYear

    InstrumentDialogInstrument.data.frontFee = Math.abs(frontFee)
    InstrumentDialogInstrument.data.frontFeeRate = frontFeeRate
    InstrumentDialogInstrument.data.frontFeeYear = frontFeeYear
    if (isEqualNum(0, InstrumentDialogInstrument.data.frontFeeRate) && !isEqualNum(0, InstrumentDialogInstrument.data.frontFee)) {
      let parseForm = JSON.parse(pFormInstrument)
      let annualized = calcAnnualizedByTerminationPaymentDate(parseForm)
      let notional = parseForm.notional
      if ('1' == InstrumentDialogInstrument.data.frontFeeYear) {
        InstrumentDialogInstrument.data.frontFeeRate = Number(InstrumentDialogInstrument.data.frontFee/notional  / annualized * 100).toFixed(2)
      }else {
        InstrumentDialogInstrument.data.frontFeeRate = Number(InstrumentDialogInstrument.data.frontFee/notional * 100).toFixed(2)
      }
    }
    if (isEqualNum(0, InstrumentDialogInstrument.data.feeRate) && !isEqualNum(0, InstrumentDialogInstrument.data.fee)) {
      let parseForm = JSON.parse(pFormInstrument)
      let annualized = calcAnnualizedByTerminationPaymentDate(parseForm)
      let notional = parseForm.notional
      if ('1' == InstrumentDialogInstrument.data.feeYear) {
        InstrumentDialogInstrument.data.feeRate = Number(InstrumentDialogInstrument.data.fee/notional  / annualized * 100).toFixed(2)
      }else {
        InstrumentDialogInstrument.data.feeRate = Number(InstrumentDialogInstrument.data.fee/notional * 100).toFixed(2)
      }
    }
    if ( !isEqualNum(0, InstrumentDialogInstrument.data.feeRate) && isEqualNum(0, InstrumentDialogInstrument.data.fee)) {
      let parseForm = JSON.parse(pFormInstrument)
      let annualized = calcAnnualizedByTerminationPaymentDate(parseForm)
      let notional = parseForm.notional
      if ('1' == InstrumentDialogInstrument.data.feeYear) {
        InstrumentDialogInstrument.data.fee = Number(notional * InstrumentDialogInstrument.data.feeRate / 100 *annualized).toFixed(2)
      }else {
        InstrumentDialogInstrument.data.fee = Number(notional * InstrumentDialogInstrument.data.feeRate /100).toFixed(2)
      }
    }
    InstrumentDialogVisible.value = true
  }
}

function openDetail(index, row) {
  handleDbclick(row)
}

function closeInstrumentDialog() {
  InstrumentDialogVisible.value = false
}
const onfrontFeeRateChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(InstrumentDialogInstrument.data.calcInstrumentForm)
  let notional = InstrumentDialogInstrument.data.calcInstrumentForm.notional
  if ('1' == InstrumentDialogInstrument.data.frontFeeYear) {
    InstrumentDialogInstrument.data.frontFee = Number(notional * InstrumentDialogInstrument.data.frontFeeRate / 100 * annualized)
  }else {
    InstrumentDialogInstrument.data.frontFee = Number(notional * InstrumentDialogInstrument.data.frontFeeRate /100)
  }
}
const onfrontFeeChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(InstrumentDialogInstrument.data.calcInstrumentForm)
  let notional = InstrumentDialogInstrument.data.calcInstrumentForm.notional
  if ('1' == InstrumentDialogInstrument.data.frontFeeYear) {
    InstrumentDialogInstrument.data.frontFeeRate = Number(InstrumentDialogInstrument.data.frontFee/notional /annualized * 100)
  }else {
    InstrumentDialogInstrument.data.frontFeeRate = Number(InstrumentDialogInstrument.data.frontFee/notional * 100)
  }
}
const onFeeChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(InstrumentDialogInstrument.data.calcInstrumentForm)
  let notional = InstrumentDialogInstrument.data.calcInstrumentForm.notional
  if ('1' == InstrumentDialogInstrument.data.feeYear) {
    InstrumentDialogInstrument.data.feeRate = Number(InstrumentDialogInstrument.data.fee/notional /annualized * 100)
  }else {
    InstrumentDialogInstrument.data.feeRate = Number(InstrumentDialogInstrument.data.fee/notional * 100)
  }
}
const onFeeRateChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(InstrumentDialogInstrument.data.calcInstrumentForm)
  let notional = InstrumentDialogInstrument.data.calcInstrumentForm.notional
  if ('1' == InstrumentDialogInstrument.data.feeYear) {
    InstrumentDialogInstrument.data.fee = Number(notional * InstrumentDialogInstrument.data.feeRate / 100 * annualized)
  }else {
    InstrumentDialogInstrument.data.fee = Number(notional * InstrumentDialogInstrument.data.feeRate /100)
  }
}
onMounted(() => {
  setTimeout(() => {
    loading.value = false
  }, 300)
  window.onresize = function temp() {
    screenHeight.value = document.documentElement.clientHeight - 350 + 'px;'
  }
})

</script>
<style scoped lang="scss">

</style>
